package org.apache.mina.example.wechat;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.executor.OrderedThreadPoolExecutor;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.http.HttpClientCodec;
import org.apache.mina.http.HttpRequestImpl;
import org.apache.mina.http.api.DefaultHttpResponse;
import org.apache.mina.http.api.HttpMethod;
import org.apache.mina.http.api.HttpRequest;
import org.apache.mina.http.api.HttpVersion;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class SendMsg extends IoHandlerAdapter{
	
//		POST https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN HTTP/1.1
//		Host: mp.weixin.qq.com
//		User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:20.0) Gecko/20100101 Firefox/20.0
//		Accept: application/json, text/javascript, */*; q=0.01
//		Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
//		Accept-Encoding: gzip, deflate
//		Content-Type: application/x-www-form-urlencoded; charset=UTF-8
//		X-Requested-With: XMLHttpRequest
//		Referer: https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN
//		Content-Length: 80
//		Cookie: remember_acct=421549014@qq.com; pgv_pvid=6791292140; ts_refer=support.weixin.qq.com/cgi-bin/mmsupport-bin/getresetpwdurl; ts_uid=4487751407; pt2gguin=o0421549014; RK=74Z7Q/j+3C; cert=aTQ8RF_kzccTu8LTFxktV8iMbQu8CgrM
//		Connection: keep-alive
//		Pragma: no-cache
//		Cache-Control: no-cache
//
//		username=421549014%40qq.com&pwd=cc37bb0193921ee3413f961ffde2f2b8&imgcode=&f=json
	
	NioSocketConnector connector = new NioSocketConnector();
	private Charset charset = Charset.forName("utf-8");
	private char[] pwd = new char[]{'k','i','d','d','i','n','g'};
	
	private SslFilter sslFilter=null;
	
	public SendMsg(SocketAddress sa){
		try {
	        // Initialize the SSLContext to work with our key managers.
	        SSLContext sslContext = SSLContext.getInstance("TLS");
	        X509TrustManager X509=  new X509TrustManager() {
	            public void checkClientTrusted(X509Certificate[] x509Certificates,
	                    String s) throws CertificateException {
	            }

	            public void checkServerTrusted(X509Certificate[] x509Certificates,
	                    String s) throws CertificateException {
	            }

	            public X509Certificate[] getAcceptedIssuers() {
	                return new X509Certificate[0];
	            }
	        };
	        sslContext.init(null, new TrustManager[]{X509}, new SecureRandom());
	        sslFilter = new SslFilter(sslContext);
			sslFilter.setUseClientMode(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		connector.getFilterChain().addLast("process", new  ExecutorFilter(new OrderedThreadPoolExecutor()));
		connector.getFilterChain().addLast("ssl", sslFilter);
		connector.getFilterChain().addLast("codec", new HttpClientCodec());
		connector.getFilterChain().addLast("log", new LoggingFilter());
		
		connector.setHandler(this);
		connector.connect(sa);
	}
	
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		SSLSession sslSession = sslFilter.getSslSession(session);
		System.out.println("send");
		HttpVersion version=HttpVersion.HTTP_1_1;
    	HttpMethod method =HttpMethod.POST;
    	String requestedPath = "/cgi-bin/login?lang=zh_CN";
    	//pwd  encryted by md5
    	String queryString ="username=421549014%40qq.com&pwd=cc37bb0193921ee3413f961ffde2f2b8&imgcode=&f=json";
//    		"signature=fe99b2962341fcc246aee89000c49afe8f7fb9f9&timestamp=1366703582&nonce=1367";
    	Map<String ,String > headers= new HashMap<String, String>();
    	headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
    	headers.put("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    	headers.put("Accept-Encoding", "gzip, deflate");
    	headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    	headers.put("X-Requested-With", "XMLHttpRequest");
    	headers.put("Referer", "https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN");
    	headers.put("Host", "mp.weixin.qq.com");
    	headers.put("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:20.0) Gecko/20100101 Firefox/20.0");
    	headers.put("Connection", "keep-alive");
    	headers.put("Content-Length", String.valueOf(queryString.length()));
    	HttpRequest request = new HttpRequestImpl(version, method, requestedPath, queryString, headers);
    	session.write(request);
	}
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		System.out.println("create");
	}
	
	@Override
		public void messageReceived(IoSession session, Object message)
				throws Exception {
		System.out.println(message);
			if( message instanceof DefaultHttpResponse){
				DefaultHttpResponse dr =(DefaultHttpResponse)message;
				System.out.println(dr);
			}else if( message instanceof IoBuffer){
				IoBuffer io = (IoBuffer)message;
				String content = io.getString(charset.newDecoder());
				System.out.println(content);
			}else{
				
			}
		}
	
	
	public static void main(String[] args) {
		SendMsg s = new SendMsg(new InetSocketAddress("mp.weixin.qq.com", 443));
		
	}
}
